var express = require('express');
var router = express.Router();

var fs = require('fs');

//import common modules
var appConfing = require("../../app_modules/dbAccess/appConfig.js");
var myTool = require("../../app_modules/common/myTool.js");
var MongoHelper =  require('../../app_modules/common/MongoHelper.js');
var gridfs = require("../../app_modules/common/gridfsTool.js");
var fileUpload = require("../../app_modules/common/UploadFile.js");
//var user =  require('../../app_modules/dbAccess/user_Mongo.js');

router.get('/', function(req, res, next) {
  res.render('index', { title: 'user' });
});



function verify(req,res,next){	
	myTool.verify(req,res,next);
}

//调用存储过程;
router.post('/invokeProcData',verify, function (req, res, next) { 
  var MetaData=myTool.getResult(req.body.MetaData,"");
  if(MetaData==""){MetaData="{}";}
  
  var functionName=myTool.getResult(req.body.functionName,"");
  if(functionName==""){
	 
    res.send({ResultCode:false,ResultMessage:"functionName is Required",MetaData:{}});
	res.header("Access-Control-Allow-Origin", "*");
  } 
  else{
    //var MetaData=JSON.stringify(MetaData);
	  MongoHelper.invokeProcData(functionName,MetaData,res);
 }
});



//上传文件
var multiparty = require('multiparty');
router.post('/uploadFile',verify, function (req, res, next) {
 var form = new multiparty.Form({ uploadDir: './public/files/upload/' });    
    form.parse(req, function (err, fields, files) {
        if(files.inputFile==undefined){
           res.send({ResultCode:false,ResultMessage:"upload error,the files is requried.",MetaData:{}});
        }
        else if(!err){
            var MetaData={};
            MetaData.url=appConfing.getAPIURL()+"files/upload/";
            MetaData.files=[];
            MetaData.imgsize=appConfing.getImsSize();
            for(i=0;i<files.inputFile.length;i++){
                var inputFile = files.inputFile[i];
                //新文件名称
                var cDate = new Date();
                var date = cDate.getFullYear().toString()+ (cDate.getMonth() + 1).toString() + cDate.getDate().toString()
                + (cDate.getHours()+1).toString()
                + cDate.getMinutes().toString()
                + cDate.getSeconds().toString()
	              + cDate.getMilliseconds().toString()
	              + i.toString();
                var fileType=inputFile.originalFilename.split(".")[1];
	              var newFileName=date+"."+fileType;
                console.log(newFileName);

                MetaData.files.push({"fileName":newFileName});

                //模式1：使用Gridfs存数据
                 // var mongoose = require('mongoose');	        			
                 // var id = new mongoose.mongo.objectid();
                 // var metadata={};
                 // metadata.filename=newfilename;
                 // gridfs.uploadfile(id,inputfile,metadata);   

                //模式2：处理文件到服务器上
                fileUpload.saveFile(inputFile,newFileName,fileType);
              }
             res.send({ResultCode:true,ResultMessage:"upload successfully.",MetaData:MetaData});
           }
        else
        {
            res.send({ResultCode:false,ResultMessage:"upload error.",MetaData:{}});
        }
           
       });
});


router.post('/deleteFile',verify, function (req, res, next) {
  var filename=myTool.getResult(req.body.filename,"");
  if(filename==""){
    res.send({ResultCode:false,ResultMessage:"filename is Required",MetaData:{}});
  }
  else{      
     var imgSize=appConfing.getImsSize();
     for(sg=0;sg<imgSize.length;sg++){
      fs.unlinkSync("./public/files/upload/" + imgSize[sg].toString()+filename);
     }     
     fs.unlinkSync("./public/files/upload/" + filename);
     res.send({ResultCode:true,ResultMessage:"the files has deleted",MetaData:{}});
  }  
});



module.exports = router;
